<!--
 * @Author: XieQiu 雪球
 * @Date: 2021-05-10 15:07:25
 * @LastEditTime: 2022-05-30 15:59:28
 * @LastEditors: 血雪球 wash0226@outlook.com
 * @Description: 巡检线路管理页面
-->
<template>
  <BaseMainSlot>
    <template v-slot:btn-box>
      <ActionBar
        :page-no="79"
        :add-active="addActive"
        :del-active="delActive"
        :edit-active="editActive"
        :cancel-active="cancelActive"
        :save-active="saveActive"
        :has-edit="false"
        :has-save="false"
        @add="add"
        @cancel="cancel"
        @edit="edit"
        @del="del"
        @save="save('formData')"
      />
    </template>
    <template v-slot:search-box>
      <el-collapse v-model="activeName" accordion @change="handleChange">
        <el-collapse-item name="1">
          <template slot="title">
            <div class="select-btns search-btns" @click.stop="changeSelect()">
              <i class="el-icon-circle-check"></i>
              <p v-if="activeName==='1'">收起筛选</p>
              <p v-if="activeName===''">展开筛选</p>
            </div>
          </template>
          <div class="search-btn search-btns" @click.stop="search()">
            <i class="el-icon-circle-check"></i>
            <p>查询</p>
          </div>
          <div class="select-box-content">
            <div class="select-box-content-name">巡查线路</div>
            <el-input v-model="routeName" clearable placeholder="请输入巡查线路名称" />
          </div>
        </el-collapse-item>
      </el-collapse>
    </template>
    <template v-slot:table-box>
      <el-table
        ref="tableData"
        v-loading="loading"
        :data="tableData"
        stripe
        border
        height="88%"
        @row-click="handleEdit"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" :selectable="(row) => { return !row.selectable }" />
        <el-table-column type="index" label="序号" width="50" />
        <el-table-column prop="routeName" label="巡查线路名称" />
        <el-table-column prop="routeName" label="关联巡查点">
          <template v-if="scope.row.routeId" slot-scope="scope">
            <el-button
              class="text-btn-cursor"
              type="text"
              size="small"
              @click="dbHandleEdit(scope.row)"
            >
              <i class="el-icon-view"></i> 查看
            </el-button>
          </template>
        </el-table-column>
        <el-table-column width="200" label="操作">
          <template v-if="scope.row.routeId" slot-scope="scope">
            <el-button
              class="text-btn-cursor"
              type="text"
              v-if="judgePermission(76, 'edit')"
              size="small"
              @click="edit"
            >
              <i class="el-icon-edit-outline"></i> 修改
            </el-button>
            <el-button
              class="text-btn-cursor cursor-delete"
              type="text"
              size="small"
              v-if="judgePermission(76, 'delete')"
              @click="handleDelete(scope.row)"
            >
              <i class="el-icon-delete"></i> 删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <Pagination
        :page-size="pageSize"
        :current-page="currentPage"
        :total-size="totalSize"
        @changePageSize="changePageSize"
        @changeCurrentPage="changeCurrentPage"
      />
    </template>

    <template v-slot:dialog>
      <el-dialog
        :title="titleText + '巡查线路信息'"
        :visible.sync="dialogFormVisible"
        :before-close="cancel"
      >
        <el-form
          ref="formData"
          label-position="left"
          :model="formData"
          :rules="rules"
          class="el-form"
        >
          <el-form-item label="巡查线路名称:" prop="routeName" class="w100p">
            <el-input v-model="formData.routeName" placeholder="请输入巡查线路名称" clearable />
          </el-form-item>
          <el-form-item label="巡查点:" prop="routePointMapperList" class="w100p pointList">
            <div class="df">
              <el-select filterable clearable v-model="nowPointId" clearable filterable @change="changenowPointId">
                <el-option
                  v-for="item in allPointList"
                  :key="item.pointId"
                  :label="item.pointName"
                  :value="item.pointId"
                />
              </el-select>
              <i class="el-icon-circle-plus-outline" @click="addPoint"></i>
            </div>
            <div class="tags">
              <div v-for="item in tagsList" :key="item.pointId" class="tag-item">
                <div class="point-name">{{ item.pointName }}</div>
                <div class="close">
                  <i class="el-icon-circle-close" @click="removeTheTag(item.pointId)"></i>
                </div>
              </div>
            </div>
          </el-form-item>
          <baidu-map
            class="map"
            style="height: 68%; width: 96%;"
            :center="center"
            :zoom="zoom"
            :scroll-wheel-zoom="true"
            map-type="BMAP_HYBRID_MAP"
          >
            <!-- @click="setCenterPoint" -->
            <bm-marker
              v-for="(item, index) in tagsList"
              :key="index"
              :position="{ lng: item.longitude, lat: item.latitude }"
              :dragging="false"
              animation="BMAP_ANIMATION_BOUNCE"
              :title="(index + 1) + '' + item.pointName"
              @click="lookDetail(item)"
            >
              <bm-label
                :content="(index + 1) + '' + item.pointName"
                :label-style="labelStyle"
                :offset="{width: -15, height: 30}"
              />
            </bm-marker>
            <bm-polyline
              stroke-style="dashed"
              stroke-color="#6ecae3"
              :stroke-opacity="1"
              :stroke-weight="4"
              :path="tagsList"
            />
            <bm-control>
              <bm-auto-complete v-model="keyword" :sug-style="{ zIndex: 999999 }">
                <el-input
                  v-model="keyword"
                  type="text"
                  placeholder="请输入地名关键字"
                  style="background-color:#003947;"
                  clearable
                >
                  <i slot="prefix" class="el-input__icon el-icon-search"></i>
                </el-input>
              </bm-auto-complete>
            </bm-control>
            <bm-local-search :keyword="keyword" :auto-viewport="true" :panel="false" />
          </baidu-map>
        </el-form>
        <div v-if="nowChanceStau !== ''" slot="footer" class="dialog-footer">
          <el-button class="cancelbtn" @click="cancel('formData')">取 消</el-button>
          <el-button class="savebtn" type="primary" @click="save('formData')">保 存</el-button>
        </div>
      </el-dialog>
      <el-dialog :title="'巡检线路信息'" :visible.sync="dialogNoticeFormVisible">
        <baidu-map
          class="map"
          style="height: 100%; width: 96%;"
          :center="center"
          :zoom="zoom"
          :scroll-wheel-zoom="true"
          map-type="BMAP_HYBRID_MAP"
        >
          <!-- @click="setCenterPoint" -->
          <bm-marker
            v-for="(item, index) in polylinePath"
            :key="index"
            :position="{ lng: item.lng, lat: item.lat }"
            :dragging="false"
            animation="BMAP_ANIMATION_BOUNCE"
            :title="(index + 1) + '_' + item.title.pointName"
            @click="lookDetail(item)"
          >
            <bm-label
              :content="(index + 1) + '_' + item.title.pointName"
              :label-style="labelStyle"
              :offset="{width: -15, height: 30}"
            />
          </bm-marker>
          <bm-polyline
            stroke-style="dashed"
            stroke-color="#6ecae3"
            :stroke-opacity="1"
            :stroke-weight="4"
            :path="polylinePath"
          />
          <bm-control>
            <bm-auto-complete v-model="keyword" :sug-style="{ zIndex: 999999 }">
              <el-input
                v-model="keyword"
                type="text"
                placeholder="请输入地名关键字"
                style="background-color:#003947;"
                clearable
              >
                <i slot="prefix" class="el-input__icon el-icon-search"></i>
              </el-input>
            </bm-auto-complete>
          </bm-control>
          <bm-local-search :keyword="keyword" :auto-viewport="true" :panel="false" />
        </baidu-map>
      </el-dialog>
    </template>
  </BaseMainSlot>
</template>

<script>
import ActionBar from "@/components/ActionBar";
import Pagination from "@/components/Pagination";
import patrolLineApi from "@/api/pond-patrol-management/patrol-line-manage";
import patrolApi from "@/api/pond-patrol-management/patrol-point-manage";
import BaseMainSlot from "@/components/BaseMainSlot/newBaseMainSlot";
import SearchBox from "@/components/SearchBox";
import { mymixin } from "@/utils/mixins";
import { mapGetters } from "vuex";
export default {
  name: "PatrolLineManage",
  components: {
    ActionBar,
    Pagination,
    BaseMainSlot,
    SearchBox
  },
  mixins: [mymixin],
  data() {
    return {
      obj: {
        name: ""
      },
      // 巡检点名称
      routeName: "",
      // 是否能输入
      canInput: false,
      // 选中的数据项数组 ID组成
      routeIdList: [],
      // 所有巡查点的列表
      allPointList: [],
      // 当前选中的巡查点ID
      nowPointId: "",
      // tag列表
      tagsList: [],
      // 选中的数据项数组 ID组成
      pointList: [],
      // 地图相关值
      // center: { lng: 120.065772, lat: 30.89475 },
      center: { lng: 120.230648, lat: 30.811543 },
      polylinePath: [],
      start: {},
      end: {},
      // zoom: 15,
      zoom: 18,
      keyword: "",
      show: false,
      position: {},
      labelStyle: {
        color: "#fffff0",
        fontSize: "12px",
        borderRadius: "8px",
        border: "none",
        backgroundColor: "#00a1c2",
        padding: "3px",
        opacity: ".8"
      },
      rules: {
        routeName: [
          { required: true, message: "请输入巡查线路名称", trigger: "blur" }
        ]
      },
      dialogTitle: "",
      dialogFormVisible: false,
      dialogNoticeFormVisible: false,
      sort: 0
    };
  },
  computed: {
    ...mapGetters({
      judgePermission: "permission/judgePermission"
    })
  },
  watch: {},
  created() {
    // 获取巡查点列表
    this.getPointList();
  },
  mounted() {
    let that = this;
    that.getdatatime();
    // 获取表格数据
    this.getTableDataList();
  },
  methods: {
    getTableDataList() {
      this.allPointList = [];
      this.loading = true;
      let params = {
        page: this.currentPage,
        size: this.pageSize,
        entity: {
          routeName: this.routeName || undefined
        }
      };
      patrolLineApi.queryPageByCondition(params).then(res => {
        this.loading = false;
        let data = res.data;
        // 赋值总条数
        if (data) {
          this.totalSize = data.totalElements;
          // 赋值数组
          this.tableData = data.content;
          this.tagsList = [];
          this.getPointList();
          this.addblankmet();
          this.resetActionBar();
        }
      });
    },
    infoWindowClose() {
      this.show = false;
    },
    infoWindowOpen() {
      this.show = true;
    },
    getPointList() {
      patrolApi.queryByCondition({}).then(res => {
        this.allPointList = res.data;
        // console.log(this.allPointList)
      });
    },
    changenowPointId(val) {
      this.nowPointId = val;
    },
    // 增加巡检点 tagsList => [{pointId: 1, pointName: '1'}] formData.routePointMapperList => tagsList
    addPoint() {
      // 新增点的对象数据数组
      // this.sort = 0
      let arr = this.allPointList.filter(
        item => item.pointId === this.nowPointId
      );
      // 判断是否存在该巡查点 inspectionPointId组成新数组
      let idList = this.tagsList.map(item => item.pointId);
      if (idList.includes(arr[0].pointId)) {
        this.$message.warning("该巡查点已经存在~");
        return;
      } else {
        if (this.tagsList === 0) {
          let sort = this.sort++;
          this.$set(arr[0], "sort", sort);
        } else {
          // this.tagsList[]
          let sort = this.tagsList.length;
          this.$set(arr[0], "sort", sort);
        }
        this.tagsList = JSON.parse(JSON.stringify(this.tagsList.concat(arr)));
        // console.log(this.tagsList);
      }
      // }
    },
    removeTheTag(pointId) {
      this.tagsList.forEach((item, index) => {
        if (item.pointId === pointId) {
          this.tagsList.splice(index, 1);
        }
      });
    },
    getdatatime() {
      // 默认显示今天
      this.formData.warehousingTime = new Date();
    },
    handleEdit(row) {
      // TODO 点击行元素后 edit
      if (!row.routeId) return;
      this.formData = JSON.parse(JSON.stringify(row));
      // console.log(row)
      this.tagsList = row.pointList;
      setTimeout(() => {
        if (this.polylinePath[0]) {
          if (this.polylinePath.length > 0) {
            var maxLng = this.polylinePath[0].lng;
            var minLng = this.polylinePath[0].lng;
            var maxLat = this.polylinePath[0].lat;
            var minLat = this.polylinePath[0].lat;
            var res;
            for (var i = this.polylinePath.length - 1; i >= 0; i--) {
              res = this.polylinePath[i];
              if (res.lng > maxLng) maxLng = res.lng;
              if (res.lng < minLng) minLng = res.lng;
              if (res.lat > maxLat) maxLat = res.lat;
              if (res.lat < minLat) minLat = res.lat;
            }
            this.center.lng = (parseFloat(maxLng) + parseFloat(minLng)) / 2;
            this.center.lat = (parseFloat(maxLat) + parseFloat(minLat)) / 2;
          }
          this.zoom = 17;
        }
      }, 600);
      this.nowPointId = "";
      this.editActive = true;
      this.saveActive = false;
      this.cancelActive = true;
      this.canInput = true;
    },

    dbHandleEdit(row) {
      if (!row.routeId) return;
      this.getDetailInspectionRouteById(row.routeId);
      setTimeout(() => {
        if (this.polylinePath[0]) {
          if (this.polylinePath.length > 0) {
            var maxLng = this.polylinePath[0].lng;
            var minLng = this.polylinePath[0].lng;
            var maxLat = this.polylinePath[0].lat;
            var minLat = this.polylinePath[0].lat;
            var res;
            for (var i = this.polylinePath.length - 1; i >= 0; i--) {
              res = this.polylinePath[i];
              if (res.lng > maxLng) maxLng = res.lng;
              if (res.lng < minLng) minLng = res.lng;
              if (res.lat > maxLat) maxLat = res.lat;
              if (res.lat < minLat) minLat = res.lat;
            }
            this.center.lng = (parseFloat(maxLng) + parseFloat(minLng)) / 2;
            this.center.lat = (parseFloat(maxLat) + parseFloat(minLat)) / 2;
          }
          this.zoom = 17;
        }
      }, 600);
      this.dialogNoticeFormVisible = true;
    },
    cancel() {
      this.nowChanceStau = "";
      this.nowPointId = "";
      this.tagsList = [];
      this.formData = {};
      this.zoom = 18;
      this.polylinePath = [];
      this.canInput = false;
      this.addActive = true;
      this.delActive = false;
      this.saveActive = false;
      this.cancelActive = false;
      this.editActive = false;
    },
    // 获取该路线的详细数据
    getDetailInspectionRouteById(id) {
      this.polylinePath = [];
      patrolLineApi.queryById(id).then(res => {
        this.tagsList = res.data.pointList;
        // console.log(this.tagsList);
        if (this.tagsList) {
          this.tagsList.forEach(item => {
            // console.log(item)
            let obj = {};
            obj["lat"] = item.latitude;
            obj["lng"] = item.longitude;
            obj["title"] = item;
            this.polylinePath.push(obj);
          });
        }
      });
    },
    lookDetail(items) {
      // console.log(items)
      this.position = items;
      this.show = true;
    },
    handleSelectionChange(list) {
      this.routeIdList = [];
      this.routeIdList = list.map(item => item.routeId);
      if (this.routeIdList.length > 0) this.delActive = true;
      else this.delActive = false;
    },
    delmessage(formData) {
      patrolLineApi.delList(this.routeIdList).then(res => {
        if (res.success) {
          this.$message.success("删除成功");
          // this.$refs[formData].resetFields();/**/
          this.getTableDataList();
        } else {
          this.$message.warning("删除失败");
        }
      });
    },
    handleDelete(data) {
      this.$confirm("此操作将永久删除该条数据, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
        
      })
        .then(() => {
          patrolLineApi.delList([data.routeId]).then(res => {
            if (res.success) {
              this.$message.success("删除成功");
              this.getTableDataList();
            } else {
              this.$message.warning("删除失败");
            }
          });
        })
        .catch(() => {
          this.$message("取消删除");
        });
    },
    save(formData) {
      this.$refs[formData].validate(valid => {
        if (valid) {
          this.polygonPath = [];
          this.tagsList.forEach(item => {
            this.polygonPath.push(item);
          });
          if (this.nowChanceStau === "edit") {
            // 编辑接口
            // 巡检点数组赋值进formData
            this.formData.pointList = this.polygonPath;
            this.formData.routePointMapperList = this.polygonPath;
            patrolLineApi.edit(this.formData).then(res => {
              if (res.success) {
                this.$message.success("修改成功！");
                this.getTableDataList();
                this.getPointList();
                this.nowPointId = "";
                this.polylinePath = [];
                this.$refs[formData].resetFields();
              } else {
                this.$message.error("修改失败！");
              }
            });
          } else if (this.nowChanceStau === "add") {
            // 新增接口
            this.formData.pointList = this.polygonPath;
            this.formData.routePointMapperList = this.polygonPath;
            patrolLineApi.add(this.formData).then(res => {
              if (res.success) {
                this.$message.success("新增成功！");
                this.getTableDataList();
                this.getPointList();
                this.nowPointId = "";
                this.tagsList = [];
                this.polylinePath = [];
                this.$refs[formData].resetFields();
              } else {
                this.$message.error("新增失败！");
              }
            });
          }
        } else {
          // console.log('error submit!!');
          return false;
        }
      });
    }
  }
};
</script>

<style scoped lang="scss">
@import "~@/styles/variables.scss";
::v-deep .content {
  .table-box {
    width: 50% !important;
  }
  .form {
    width: 48% !important;
  }
}
::v-deep .el-form-item__label {
  text-align: end;
  min-width: 120px !important;
}
.pointList {
  i {
    font-size: 30px;
    margin-left: 10px;
    cursor: pointer;
  }
  .noClick {
    cursor: not-allowed;
  }
  .df {
    display: flex;
    align-items: center;
    width: 100%;
  }
  ::v-deep .el-form-item__content {
    flex-direction: column;
  }
  .label {
    min-width: 120px !important;
  }
  .tags {
    width: 100%;
    display: flex;
    flex-wrap: wrap;
    .tag-item {
      height: 30px;
      padding: 5px 10px;
      background-color: #00a1c2;
      border-radius: 8px;
      display: flex;
      align-items: center;
      margin-top: 10px;
      margin-right: 10px;
      i {
        font-size: 14px;
      }
    }
  }
}
::v-deep .form {
  position: relative;
}
.map {
  position: absolute;
  bottom: 0px;
  width: 100%;
  height: 100%;
  touch-action: none;
}
.lng {
  ::v-deep .el-input__inner {
    min-width: 70px;
  }
}
.lat {
  ::v-deep .el-form-item__label {
    text-align: end;
    min-width: 100px !important;
  }
}
::v-deep .BMap_pop {
  left: 102px !important;
}
/*地图标题*/
::v-deep .BMap_bubble_title {
  // color:white;
  font-size: 13px;
  font-weight: bold;
  text-align: left;
  padding-left: 5px;
  padding-top: 5px;
  width: 10px;
  // border-bottom:1px solid gray;
  // background-color:#0066b3;
}
/* 消息内容 */
::v-deep .BMap_bubble_content {
  background-color: white;
  padding-left: 5px;
  padding-top: 5px;
  padding-bottom: 10px;
}
/* 内容 */
::v-deep .BMap_pop div:nth-child(9) {
  top: 35px !important;
  border-radius: 7px;
}
/* 左上角删除按键 */
::v-deep .BMap_pop img {
  top: 40px !important;
  left: 5555px !important;
}
::v-deep .BMap_top {
  display: none;
}
::v-deep .BMap_bottom {
  display: none;
}
::v-deep .BMap_center {
  display: none;
}
/* 隐藏边角 */
::v-deep .BMap_pop div:nth-child(1) div {
  display: none;
}
::v-deep .BMap_pop div:nth-child(4) {
  display: none;
}
::v-deep .BMap_pop div:nth-child(3) {
  display: none;
}
::v-deep .BMap_pop div:nth-child(5) {
  display: none;
}
::v-deep .BMap_pop div:nth-child(6) {
  display: none;
}
::v-deep .BMap_pop div:nth-child(7) {
  display: none;
}
::v-deep .BMap_pop div:nth-child(8) {
  display: none;
}
::v-deep .BMap_pop div:nth-child(9) {
  box-sizing: content-box;
  width: 110px !important;
  /* height: 55px; */
  position: absolute;
  left: 16px;
  top: 16px;
  z-index: 10;
  overflow: hidden;
}
::v-deep .BMap_shadow {
  display: none;
}
::v-deep .el-dialog__wrapper {
  .el-dialog {
    height: 78vh;
    margin-top: 0vh !important;

    .el-dialog__body {
      overflow: hidden;
      position: relative;
      height: 84%;
    }
  }
}
::v-deep .dialog {
  .el-dialog__headerbtn {
    top: 0;
    right: 10px;
  }
  .el-dialog {
    margin-top: 0vh !important;
    min-width: 15%;
    width: 200px !important;
    height: auto !important;
  }
}
</style>
